/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ticketmaster.businesslogic;

import javax.security.cert.CertificateException;
import ticketmaster.businessobject.Administrator;
import ticketmaster.businessobject.Clerk;
import ticketmaster.businessobject.Customer;
import ticketmaster.common.UserRoles;
import ticketmaster.dao.DAOFactory;
import ticketmaster.dao.UserDAO;
import ticketmaster.dataobject.User;
import ticketmaster.security.Encryption;

/**
 *
 * @author Wei Liu
 */
public class LoginController
{
    private UserDAO userDAO;

    public LoginController()
    {
        
    }

    public ticketmaster.businessobject.User validateUser(String username, String password) throws CertificateException
    {
        User user = new User();
        user.setUsername(username);
        user.setPassword(Encryption.md5(password));

        User validatedUser = this.getUserDAO().findUser(user);

        ticketmaster.businessobject.User loginUser = null;

        if(validatedUser != null)
        {
            if(validatedUser.getUserRoleID() == UserRoles.Customer.ordinal())
            {
                loginUser = new Customer();
                loginUser.setRole(UserRoles.Customer);
            }
            else if(validatedUser.getUserRoleID() == UserRoles.Clerk.ordinal())
            {
                loginUser = new Clerk();
                loginUser.setRole(UserRoles.Clerk);
            }
            else if(validatedUser.getUserRoleID() == UserRoles.Administrator.ordinal())
            {
                loginUser = new Administrator();
                loginUser.setRole(UserRoles.Administrator);
            }

            loginUser.setUserID(validatedUser.getUserID());
            loginUser.setUsername(username);
            loginUser.setPassword(password);

            ticketmaster.dataobject.Customer customerNew = new ticketmaster.dataobject.Customer();
            customerNew.setCustomerID(validatedUser.getUserID());

            DAOFactory.getInstance().getCustomerDAO().findCustomer(customerNew);

            loginUser.setCustFirstName(customerNew.getFirstName());
            loginUser.setCustLastName(customerNew.getLastName());
            

        }
        else
        {
            throw new CertificateException("User does not exist!");
        }

        return loginUser;
    }

    /**
     * @return the userDAO
     */
    public UserDAO getUserDAO()
    {
        if(userDAO == null)
            userDAO = DAOFactory.getInstance().getUserDAO();
        return userDAO;
    }
}
